package leetcode.medium.maxancestordiff;

import util.adt.TreeNode;

/**
 * <a href="https://leetcode.cn/problems/maximum-difference-between-node-and-ancestor/">链接</a>
 */
public class Solution {
    int ans = 0;

    public int maxAncestorDiff(TreeNode root) {
        dfs(root, root.val, root.val);
        return ans;
    }

    private void dfs(TreeNode root, int min, int max) {
        if (root == null) {
            return;
        }
        int val = root.val;
        ans = Math.max(ans, Math.max(Math.abs(val - min), Math.abs(val - max)));
        min = Math.min(min, val);
        max = Math.max(max, val);
        dfs(root.left, min, max);
        dfs(root.right, min, max);
    }
}
